package com.dongwei.junitlearn.chapter3.controller.impl;

import java.util.HashMap;
import java.util.Map;

import com.dongwei.junitlearn.chapter3.controller.iface.Controller;
import com.dongwei.junitlearn.chapter3.controller.iface.Request;
import com.dongwei.junitlearn.chapter3.controller.iface.RequestHandler;
import com.dongwei.junitlearn.chapter3.controller.iface.Response;

public class DefaultController implements Controller {
	private Map<String, RequestHandler> requestHandlers = new HashMap<String, RequestHandler>();

	public Response processRequest(Request request) {
		RequestHandler requestHandler = getRequestHandler(request);
		try {
			return requestHandler.processRequest(request);
		} catch (Exception e) {
			return new ErrorResponse(request, e);
		}
	}

	protected RequestHandler getRequestHandler(Request request) {
		if (this.requestHandlers.containsKey(request.getName())) {
			return requestHandlers.get(request.getName());
		} else {
			String message = "Cannot find handler for request name [" + request.getName() + "]";
			throw new RuntimeException(message);
		}
	}

	public void addHandler(Request request, RequestHandler requestHandler) {
		String requestName = request.getName();
		if (this.requestHandlers.containsKey(requestName)) {
			throw new RuntimeException("A request handler has already been registered for request name [" + requestName
					+ "]");
		} else {
			this.requestHandlers.put(requestName, requestHandler);
		}
	}

}
